<template>
  <div class="contren">
    <div class="img-v" v-for="(item, indexs) in imgbox" :key="indexs">
      <div class="img-tit">
        <span style="color: red;" v-if="item.bitian == 1">*</span>
        {{ item.cn_name }}
      </div>

      <div class="img-box">
        <div class="img" v-for="(items, index) in item.imglist" :key="index">
          <el-image
            @click="previewImage(item, index)"
            :src="items.suoluet"
            fit="cover"
            class="upload-image"
            :preview-src-list="getPreviewList(item.imglist)"
            :initial-index="index"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
                <span>加载失败</span>
              </div>
            </template>
          </el-image>
          <div class="del" @click="deleteImage(index, item)" v-if="item.eidt == 2">
            ×
          </div>
        </div>
        <div class="img-t" @click="chooseImage(item, indexs)" v-if="item.eidt > 0">
          <el-image 
            src="https://xcxzlcs.haozskj.com/xcx/images/imgadd.jpg"
            fit="cover"
            class="add-image"
          >
            <template #error>
              <div class="add-img-placeholder">
                <el-icon><Plus /></el-icon>
                <span>添加图片</span>
              </div>
            </template>
          </el-image>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Delete, Plus } from '@element-plus/icons-vue'
import { Base64 } from 'js-base64'
import request from '@/utils/request.js'

// Props定义 - 完全按照uni-app的结构
const props = defineProps({
  imgs: {
    type: Array,
    default: () => []
  },
  obj: {
    type: Object,
    default: () => ({})
  },
  imgUrl: {
    type: String,
    default: ''
  },
  faid: {
    type: Number,
    default: 0
  },
  isgps: {
    type: Boolean,
    default: false
  }
})

// Emits定义
const emit = defineEmits(['child-event'])

// 响应式数据
const imgbox = ref([])

// 监听props变化 - 完全按照uni-app的watch逻辑
watch(() => props.imgs, (newVal) => {
  imgbox.value = newVal || []
  // console.log('测试打印数据 UploadImg props.imgs 更新:', newVal)
}, { immediate: true, deep: true })

// 计算预览图片列表
const getPreviewList = (imglist) => {
  if (!imglist || !Array.isArray(imglist)) return []
  return imglist.map(item => item.datu || item.suoluet).filter(Boolean)
}

// 深拷贝工具函数 - 完全按照uni-app的zhuanjson方法
const zhuanjson = (item) => {
  return JSON.parse(JSON.stringify(item))
}

// 支持多类型文件选择和上传
const getAccept = (ctype) => {
  if (ctype === 'pdf') return '.pdf,application/pdf'
  if (ctype === 'img' || ctype === 'jpg' || ctype === 'png') return 'image/*'
  if (ctype === 'all' || ctype === 'pdf_img') return '.pdf,application/pdf,image/*'
  return ''
}

const chooseImage = (items, index) => {
  const item = zhuanjson(items)
  // console.log('测试打印数据 选择图片，isgps:', props.isgps, 'ctype:', item.ctype)

  // 支持多类型
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = getAccept(item.ctype)
  input.multiple = true // 支持多选，最多9个
  input.style.display = 'none'

  input.onchange = async (event) => {
    const files = Array.from(event.target.files)
    if (files.length === 0) return
    // 限制最多9个
    const limitedFiles = files.slice(0, 9)

    // 构建imgbianhao
    let imgbianhao = ''
    const objs = zhuanjson(props.obj)
    const imgbhzd = zhuanjson(imgbox.value[index].imgbhzd || [])
    imgbhzd.forEach(key => {
      if (key in objs) {
        if (imgbianhao == '') {
          imgbianhao = objs[key]
        } else {
          imgbianhao += '_' + objs[key]
        }
      }
    })

    // 构建formData
    const formData = {
      ctype: 'app_addtupian',
      imgleixing: '',
      shuiyin: '1',
      id: '0',
      tupianbt: '',
      zileix: item.en_name,
      leixingbh: imgbianhao,
      username: getUserName(),
      jiedaodizhi: '',
      jingweidu: '',
      faid: props.faid
    }
    if (props.isgps) {
      const gpsData = getGpsData()
      formData.jiedaodizhi = gpsData.jiedaodizhi
      formData.jingweidu = gpsData.jingweidu
    }
    // console.log('测试打印数据 地址信息 (按uni-app结构):', formData)
    // 上传
    await uploadImage(limitedFiles, formData, index)
  }
  document.body.appendChild(input)
  input.click()
  document.body.removeChild(input)
}

// 预览图片 - 完全按照uni-app的previewImage方法逻辑
const previewImage = (imageLists, index) => {
  const imageList = imageLists.imglist
  // console.log('测试打印数据 预览图片:', imageLists, index)
  
  if (imageLists.ctype == 'img') {
    // 图片类型 - 使用Element Plus的预览功能
    // Element Plus的el-image组件会自动处理预览
    return
  } else {
    // 非图片类型 - 按照uni-app逻辑处理
    if (imageList[index].datu.indexOf('jpg') > -1 || imageList[index].datu.indexOf('png') > -1) {
      // 图片格式，使用Element Plus预览
      return
    } else {
      // PDF等文件格式，直接打开 - 模拟uni-app的下载和打开逻辑
      ElMessage.info('正在下载文件...')
      
      // 直接打开文件，模拟uni-app的openDocument
      window.open(imageList[index].datu, '_blank')
    }
  }
}

// 删除图片 - 完全按照uni-app的deleteImage方法逻辑
const deleteImage = async (index, imageLists) => {
  // console.log('测试打印数据 删除图片:', imageLists)
  const imageList = imageLists.imglist
  
  try {
    // 模拟uni.showModal
    await ElMessageBox.confirm(
      '确定删除该图片吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 完全按照uni-app的删除逻辑
    const bs64_cs = {
      openid: getDeviceId(), // 模拟uni.getSystemInfoSync().deviceId
      id: imageList[index].id
    }
    
    const cs = {
      ctype: 'app_zlxt_xq_del_img',
      bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
      bs64_obj: Base64.encode(JSON.stringify(props.obj)),
      bs64_list: '',
      ids: '',
      faid: props.faid
    }
    
    // console.log('测试打印数据 删除请求参数 (按uni-app结构):', cs)
    
    const res = await request.post('/xcx/Ajax/Ajax_apppost.ashx', { canshu: cs })
    
    // console.log('测试打印数据 删除响应:', res)
    
    if (res.leixing == 'ok') {
      imageList.splice(index, 1)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      // console.error('测试打印数据 删除图片失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传图片到服务器 - 完全按照uni-app的uploadImage方法逻辑
const uploadImage = async (imglist, formData, index) => {
  try {
    // 模拟uni-app的多文件上传逻辑
    const uploadTasks = imglist.map((file, fileIndex) => {
      // console.log('测试打印数据 准备上传文件:', file.name)
      
      return new Promise((resolve, reject) => {
        // 使用FormData模拟uni.uploadFile
        const uploadFormData = new FormData()
        uploadFormData.append('file', file) // name字段按uni-app设为'file'
        
        // 添加formData中的所有字段
        Object.keys(formData).forEach(key => {
          uploadFormData.append(key, formData[key])
        })
        
        // 构建上传URL - 完全按照uni-app的URL结构
        const uploadUrl = `${getYuming()}/xcx/ajax/imgUpload_zj.ashx`
        
        // console.log('测试打印数据 上传URL (按uni-app结构):', uploadUrl)
        // console.log('测试打印数据 上传参数 (按uni-app结构):', formData)
        
        // 使用fetch模拟uni.uploadFile
        fetch(uploadUrl, {
          method: 'POST',
          body: uploadFormData
        })
        .then(response => {
          if (response.status === 200) {
            return response.json()
          } else {
            throw new Error('上传失败')
          }
        })
        .then(data => {
          // console.log('测试打印数据 上传响应 (按uni-app结构):', data)
          resolve(data)
        })
        .catch(err => {
          // console.error('测试打印数据 上传失败:', err)
          reject(err)
        })
      })
    })
    
    // 处理所有上传结果 - 完全按照uni-app的Promise.all逻辑
    try {
      const results = await Promise.all(uploadTasks)
      
      ElMessage.success('上传成功')
      // console.log('测试打印数据 所有图片地址 (按uni-app结构):', results)
      
      // 按照uni-app的逻辑更新imglist
      results.forEach(file => {
        // console.log('测试打印数据 添加图片到列表:', file)
        if (file && file.imglist && file.imglist[0]) {
          imgbox.value[index].imglist.push(file.imglist[0])
        }
      })
      
    } catch (err) {
      ElMessage.error('上传失败')
  
    }
    
  } catch (error) {
 
    ElMessage.error('上传失败，请重试')
  }
}

// 辅助函数 - 模拟uni-app的存储和系统信息获取
const getUserName = () => {
  try {
    const userinfo = localStorage.getItem('userinfo')
    if (userinfo) {
      return JSON.parse(userinfo).user_zsxm || ''
    }
  } catch (e) {
    console.warn('获取用户信息失败:', e)
  }
  return ''
}

const getDeviceId = () => {
  // 模拟uni.getSystemInfoSync().deviceId
  return localStorage.getItem('openid') || localStorage.getItem('deviceId') || '17524180246839845722'
}

const getYuming = () => {
  // 模拟uni.getStorageSync('yuming')
  return localStorage.getItem('yuming') || 'https://vue.haozskj.com'
}

const getGpsData = () => {
  // 模拟uni.getStorageSync('gps')
  try {
    const gps = localStorage.getItem('gps')
    if (gps) {
      return JSON.parse(gps)
    }
  } catch (e) {
    console.warn('获取GPS信息失败:', e)
  }
  return {
    jiedaodizhi: '',
    jingweidu: ''
  }
}
</script>

<style lang="scss" scoped>
.contren {
  width: 100%;
}

.img-v {
  width: 100%;
}

.img-tit {
  padding: 20rpx;
  // 转换rpx为px，1rpx ≈ 0.5px
  padding: 10px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  background-color: #f5f7fa;
}

.img-box {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 0 20rpx;
  // 转换rpx为px
  padding: 0 10px;
  min-height: 120rpx;
  // 转换rpx为px
  min-height: 60px;
  flex-flow: row wrap;
  box-sizing: border-box;
  border: 1px solid #e4e7ed;
  background-color: #fff;
}

.img {
  height: 80rpx;
  // 转换rpx为px
  height: 40px;
  width: 40px;
  position: relative;
  margin: 18rpx;
  // 转换rpx为px
  margin: 9px;
  border: 1rpx solid #ccc;
  // 转换rpx为px
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.del {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 20px;
  height: 20px;
  background: red;
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 18px;
  cursor: pointer;
  font-size: 12px;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.del:hover {
  background: #d9001b;
  transform: scale(1.1);
}

.img-t {
  margin: 18rpx;
  // 转换rpx为px
  margin: 9px;
  width: 40px;
  height: 40px;
  border: 2px dashed #c0c4cc;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
}

.img-t:hover {
  border-color: #409eff;
}

.add-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.add-img-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 10px;
  background-color: #fafafa;
}

.add-img-placeholder .el-icon {
  font-size: 16px;
  margin-bottom: 2px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 10px;
}

.image-error .el-icon {
  font-size: 16px;
  margin-bottom: 2px;
}

// 响应式设计
@media (max-width: 768px) {
  .img-tit {
    padding: 8px;
    font-size: 13px;
  }
  
  .img-box {
    padding: 0 8px;
    min-height: 50px;
  }
  
  .img,
  .img-t {
    width: 35px;
    height: 35px;
    margin: 6px;
  }
  
  .del {
    width: 18px;
    height: 18px;
    font-size: 10px;
    line-height: 16px;
    top: -9px;
    right: -9px;
  }
}
</style> 